package me.android.library.ui.config;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import me.android.library.utils.android.ResourcesUtil;
import mylab.base.foundation.template.pojo.BaseStringIDPojo;
import mylab.utils.common.CastUtil;
import mylab.utils.common.ReflectUtil;

@Slf4j
@Data
@EqualsAndHashCode(callSuper = true)
public abstract class BaseElement<T> extends BaseStringIDPojo implements UiElement<T> {

    protected String implClass;
    protected String iconRes;

    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    @ToString.Exclude
    @EqualsAndHashCode.Exclude
    protected T t;

    public String getName() {
        return ResourcesUtil.getStringOrFromRes(name);
    }

    public int getIconResId() {
        return ResourcesUtil.getResourceId(iconRes);
    }

    @Override
    public T get() {
        if (t != null) {
            return t;
        }

        Preconditions.checkState(!Strings.isNullOrEmpty(implClass), "clazz is null");
        try {
            t = CastUtil.cast(ReflectUtil.newInstance(implClass));
        } catch (Exception e) {
            log.warn("uiConfig implClass not be a valid instance", e);
        }

        return t;
    }
}
